package com.pocketsweet.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVInstallation;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FunctionCallback;
import com.avos.avoscloud.LogInCallback;
import com.avos.avoscloud.PushService;
import com.avos.avoscloud.RefreshCallback;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.HanziToPinyin;
import com.pocketsweet.C;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLCache;
import com.pocketsweet.MLContext;
import com.pocketsweet.R;
import com.pocketsweet.chatui.Constant;
import com.pocketsweet.chatui.domain.User;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.ui.CreateUserInfo;
import com.pocketsweet.ui.Main;
import com.pocketsweet.ui.Splash;
import com.pocketsweet.ui.TempMain;
import com.pocketsweet.ui.VerifySmsCode;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.utils.MD5;
import com.pocketsweet.utils.ShareReferanceUtils;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.bean.StatusCode;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SocializeClientListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMDataListener;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;

public class LoginService {
    public UMSocialService mController;
    private Context ctx;
    private boolean isLogin = false;
    private LoadingDailog mLoadingDialog;
    private boolean isRegisterHuanxin = false;
    String uid = null;
    String access_token = null;
    String expiresAt = null;
    String reg_uid = null;
    String reg_access_token = null;
    String reg_expiresAt = null;
    MLCache mlCache;

    private loginCompleteListener mLoginCompleteListener;

    public LoginService(Context context) {
        ctx = context;
        mController = UMServiceFactory.getUMSocialService("com.umeng.login");
        mLoadingDialog = ToolKits.createLoadingDialog(ctx, "登陆中...");
        mLoadingDialog.setText("加载中");
        // 设置微信
        // setWeixn();
        // 设置qq和qqzone
        // setQQ();
        // 设置新浪微博
        // setSina();
    }

    private void startLogin(SHARE_MEDIA umengType, final String leabCloudType) {
        mController.doOauthVerify(ctx, umengType, new UMAuthListener() {
            @Override
            public void onError(SocializeException e, SHARE_MEDIA platform) {
                mLoadingDialog.dismiss();
                Toast.makeText(ctx, "登录失败...", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(Bundle value, SHARE_MEDIA platform) {
                uid = value.getString("uid");
                access_token = value.getString("access_token");
                expiresAt = value.getString("expires_in");
                // Log.e("==getValues", value.toString());
                if (!TextUtils.isEmpty(uid)) {
                    getUserInfo(platform, leabCloudType);
                } else {
                    Toast.makeText(ctx, "授权失败", Toast.LENGTH_SHORT).show();
                    if (mLoadingDialog.isShowing() && !((Activity) ctx).isFinishing())
                        mLoadingDialog.dismiss();
                }
            }

            @Override
            public void onCancel(SHARE_MEDIA platform) {
                if (!((Activity) ctx).isFinishing() && mLoadingDialog.isShowing())
                    mLoadingDialog.dismiss();
            }

            @Override
            public void onStart(SHARE_MEDIA platform) {
                if (!((Activity) ctx).isFinishing() && !mLoadingDialog.isShowing())
                    mLoadingDialog.show();
            }
        });
    }

    public void login(final String phone, final String passwordStr) {
        final Dialog dialog = new Dialog(ctx, R.style.MyDialog);
        // 设置它的ContentView
        dialog.setContentView(R.layout.dialog_login_fail);
        final TextView btn_sure = (TextView) dialog.findViewById(R.id.btn_sure);
        final TextView txt_msg = (TextView) dialog.findViewById(R.id.txt_msg);

        if (phone.length() != 11) {
            ToolKits.toast(ctx, "手机号码格式错误");
            return;
        }
        if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(passwordStr)) {
            ToolKits.toast(ctx, "账号密码不能为空");
            return;
        }
        mLoadingDialog.setTitle("登录中");
        if (!mLoadingDialog.isShowing())
            mLoadingDialog.show();
        MLUser.logInInBackground(phone, passwordStr,
                new LogInCallback<AVUser>() {

                    @Override
                    public void done(final AVUser user, AVException e) {
                        if (e == null) {
                            if (UserService.getCurrentUser().getStatus() == C.USER_STATUS_DISABLE) {
                                isLogin = false;
                                ToolKits.toast(ctx, "对不起该账号已被查封");
                                logOut();
                                mLoadingDialog.dismiss();
                            } else {
                                // 登录成功，保存账号和密码
                                MLApplication.getInstance().isLogin = true;
                                ShareReferanceUtils share = new ShareReferanceUtils(
                                        MLApplication.getContext(), "USER");
                                share.setStringValue("user", user.getUsername());
                                share.setStringValue("userId",
                                        user.getObjectId());
                                share.setStringValue("pass", passwordStr);
                                // 用户关注channel
                                initChannel();
                                if (UserService.getCurrentUser().getIsInited() != 1) {
                                    ToolKits.toast(ctx, "您的账号信息不全，请先完善信息");
                                    Intent r = new Intent(ctx,
                                            CreateUserInfo.class);
                                    ctx.startActivity(r);
                                    ((Activity) ctx).finish();
                                    return;
                                }
                                loginHuanxin("");// 登陆环信
                            }
                        } else {
                            // 登陆失败
                            isLogin = false;
                            logOut();
                            if (mLoadingDialog.isShowing())

                                mLoadingDialog.dismiss();
                            // 登录失败
                            if (e.getCode() == 215) {// 未验证手机号
                                dialog.show();
                                txt_msg.setText("未验证手机号");
                                btn_sure.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                        Intent r = new Intent(ctx,
                                                VerifySmsCode.class);
                                        r.putExtra("phone", phone);
                                        ctx.startActivity(r);
                                    }
                                });
                            } else if (e.getCode() == 210) {
                                dialog.show();
                                txt_msg.setText("密码错误，请重新填写");
                                btn_sure.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                });
                            } else if (e.getCode() == 211 || e.getCode() == 213) {
                                dialog.show();
                                txt_msg.setText("用户不存在，请重新填写");
                                btn_sure.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                });
                            } else if (e.getCode() == 1) {
                                dialog.show();
                                txt_msg.setText("请输入你的密码");
                                btn_sure.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                });
                            } else {
                                dialog.show();
                                txt_msg.setText("登陆失败，请检查网络，稍后重试");
                                btn_sure.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                });
                            }
                        }
                    }
                });
    }

    public void loginWithSina() {
        // 设置新浪SSO handler
        mController.getConfig().setSsoHandler(new SinaSsoHandler());
        startLogin(SHARE_MEDIA.SINA, AVUser.AVThirdPartyUserAuth.SNS_SINA_WEIBO);
    }

    public void loginWithQQ() {
        startLogin(SHARE_MEDIA.QQ, "qq");
    }

    public void loginWithWeChat() {
        UMWXHandler wxHandler = new UMWXHandler(ctx, "wxaa055b4833fdbf4a",
                "c4f199bd5983ae9309c8bcb4f3bcd0e4");
        wxHandler.addToSocialSDK();
        startLogin(SHARE_MEDIA.WEIXIN,
                AVUser.AVThirdPartyUserAuth.SNS_TENCENT_WEIXIN);
    }

    /**
     * 如果授权成功，则获取用户信息
     */
    public void getUserInfo(final SHARE_MEDIA platform, final String type) {
        mController.getPlatformInfo(ctx, platform, new UMDataListener() {
            @Override
            public void onStart() {
                if (mLoadingDialog.isShowing())
                    mLoadingDialog.show();
            }

            @Override
            public void onComplete(int status, final Map<String, Object> info) {
                if (status == StatusCode.ST_CODE_SUCCESSED && info != null) {
                    // Log.e("=getUser", "begin to getUserInfo：" +
                    // info.toString());

                    StringBuilder sb = new StringBuilder();
                    Set<String> keys = info.keySet();
                    for (String key : keys) {
                        sb.append(key + "=" + info.get(key).toString() + "\r\n");
                    }
                    // Log.e("TestData", sb.toString());
                    if (StringUtils.isEmpty(access_token)) {
                        access_token = info.get("access_token").toString();
                    }
                    if (StringUtils.isEmpty(uid)) {
                        uid = info.get("uid").toString();
                    }
                    AVUser.AVThirdPartyUserAuth auth = new AVUser.AVThirdPartyUserAuth(
                            access_token, "", type, uid);
                    AVUser.loginWithAuthData(auth, new LogInCallback<AVUser>() {

                        @Override
                        public void done(AVUser user, AVException e) {
                            if (e == null) {
                                // 恭喜你，已经和我们的AVUser绑定成功
                                if (UserService.getCurrentUser().getStatus() == C.USER_STATUS_DISABLE) {
                                    ToolKits.toast(ctx, "对不起该账号已被查封");
                                    // Login.logOut();
                                    mLoadingDialog.dismiss();

                                } else {
                                    // Log.e("=succeed=", "duang!!!!!!!!!");
                                    // 登录成功，保存账号和密码
                                    MLApplication.getInstance()
                                            .setIsLogin(true);
                                    ShareReferanceUtils share = new ShareReferanceUtils(
                                            MLApplication.getContext(), "USER");
                                    share.setStringValue("access_token",
                                            access_token);
                                    share.setStringValue("uid", uid);
                                    share.setStringValue("userId",
                                            user.getObjectId());
                                    share.setStringValue("type", type);
                                    // Log.e("==login", "==login==uid:" + uid);
                                    // Log.e("==login", "==login==type:" +
                                    // type);
                                    // Log.e("==login", "==login==access_token:"
                                    // + access_token);
                                    MLUser currUser = UserService
                                            .getCurrentUser();
                                    // 用户关注channel
                                    initChannel();
                                    if (UserService.getCurrentUser()
                                            .getIsInited() != 1) {
                                        String nickname;
                                        if (info.get("screen_name") != null) {
                                            nickname = info.get("screen_name")
                                                    .toString();
                                        } else {
                                            nickname = info.get("nickname")
                                                    .toString();
                                        }
                                        currUser.setNickname(nickname);
                                        // currUser.saveInBackground();
                                        ToolKits.toast(ctx, "您的账号信息不全，请先完善信息");
                                        Intent r = new Intent(ctx,
                                                CreateUserInfo.class);
                                        r.putExtra("nickname", nickname);
                                        r.putExtra("type", type);
                                        // r.putExtra("gender",
                                        // info.get("gender").toString());
                                        // r.putExtra("location",
                                        // info.get("location")
                                        // .toString());
                                        // r.putExtra("profile_image_url",
                                        // info.get("profile_image_url").toString());
                                        ctx.startActivity(r);
                                        ((Activity) ctx).finish();
                                        mLoadingDialog.dismiss();
                                        return;
                                    }
                                    loginHuanxin(type);

                                }
                            } else {
                                e.printStackTrace();
                            }
                        }

                    });
                    return;

                }
            }
        });
    }

    private void initChannel() {
        PushService
                .subscribe(ctx, UserService.getCurrentUserId(), Splash.class);
        if (UserService.getCurrentUser().getType() == C.USER_TYPE_LOVER
                || UserService.getCurrentUser().getType() == C.USER_TYPE_RECOMMENDED) {
            if (UserService.getCurrentUser().getGender() == C.USER_GENDER_MALE) {
                PushService.subscribe(ctx, "SweetMale", Main.class);
            } else if (UserService.getCurrentUser().getGender() == C.USER_GENDER_FEMALE) {
                PushService.subscribe(ctx, "SweetFemale", Main.class);
            }
        }

    }

    private UMSocialService setSinaResult() {
        /** 使用SSO授权必须添加如下代码 */
        return mController;
    }

    public void deteteOauth() {
        mController.deleteOauth(ctx, SHARE_MEDIA.QQ,
                new SocializeClientListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onComplete(int status, SocializeEntity entity) {
                        if (status == 200) {
                            Toast.makeText(ctx, "删除成功.", Toast.LENGTH_SHORT)
                                    .show();
                        } else {
                            Toast.makeText(ctx, "删除失败", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                });
    }

    public void registerHuanxin(final String type) {
        // 验证通过后注册环信
        if (isRegisterHuanxin == true) { // 若已注册过环信
            loginHuanxin(type); // 登录环信并跳到首页
            return;
        }
        if (!((Activity) ctx).isFinishing() && !mLoadingDialog.isShowing())
            mLoadingDialog.show();
        UserService.getCurrentUser().refreshInBackground(
                new RefreshCallback<AVObject>() {

                    @Override
                    public void done(AVObject arg0, AVException e) {
                        // TODO Auto-generated method stub
                        if (e == null) {
                            Map<String, Object> params = new HashMap<String, Object>();
                            MLUser user = UserService.getCurrentUser();
                            params.put("username", user.getObjectId());
                            params.put("nickname", user.getNickname());
                            params.put("password", MD5.md5(user.getObjectId()));
                            AVCloud.callFunctionInBackground("register",
                                    params, new FunctionCallback<Object>() { // 注册环信

                                        @Override
                                        public void done(Object arg0,
                                                         AVException e) {

                                            if (e == null) {
                                                // //
                                                // 如果注册环信没有错误跳转到验证
                                                mLoadingDialog.dismiss();
                                                ToolKits.toast(ctx,
                                                        "恭喜您注册成功，正在登录中");
                                                // Log.e("==register",
                                                // "register huanxin succeed");

                                                isRegisterHuanxin = true;
                                                loginHuanxin(type);
                                            } else {
                                                ToolKits.toast(ctx, "注册失败");
                                                isRegisterHuanxin = false;
                                                mLoadingDialog.dismiss();
                                            }
                                        }

                                    });
                        } else {
                            ToolKits.toast(ctx, "注册失败");
                        }
                    }
                });

    }

    public void loginHuanxin(final String type) {
        // 登陆环信聊天
        if (!((Activity) ctx).isFinishing() && !mLoadingDialog.isShowing())
            mLoadingDialog.show();
        if (UserService.getCurrentUser() == null) {
            return;
        }
        EMChatManager.getInstance().login(UserService.getCurrentUserId(),
                MD5.md5(UserService.getCurrentUser().getObjectId()),
                new EMCallBack() {

                    @Override
                    public void onSuccess() {
                        // 登录成功，保存账号和密码
                        String user = MLContext.getUserLogin("user");
                        String pwd = MLContext.getUserLogin("pass");
                        String uid = MLContext.getUserLogin("uid");
                        String type = MLContext.getUserLogin("type");
                        String access_token = MLContext
                                .getUserLogin("access_token");
                        if (user.equals("") && pwd.equals("") && uid.equals("")
                                && access_token.equals("")) {
                            ShareReferanceUtils share = new ShareReferanceUtils(
                                    MLApplication.getContext(), "USER");
                            share.setStringValue("access_token", access_token);
                            share.setStringValue("uid", uid);
                            share.setStringValue("type", type);

                        }
                        // Log.e("==login", "==login==uid:" + uid);
                        // Log.e("==login", "==login==type:" + type);
                        // Log.e("==login", "==login==access_token:"
                        // + access_token);
                        //
                        MLUser currentUser = UserService.getCurrentUser();
                        EMChatManager.getInstance().deleteConversation(
                                Constant.NEW_CHAT_APPLY);// 删掉通话申请
                        if (currentUser.getType() != C.USER_TYPE_NORMAL) {
                            EMChatManager.getInstance().deleteConversation(
                                    Constant.NEW_FRIENDS_USERNAME);// 删掉好友申请
                        }
                        AVCloud.callFunctionInBackground("getNetTime", null,
                                new FunctionCallback<Long>() {

                                    @Override
                                    public void done(Long time, AVException e) {
                                        if (e == null) {
                                            Date currentDate = new Date(time);
                                            MLUser currentUser = new MLUser();
                                            currentUser.setObjectId(UserService.getCurrentUserId());
                                            currentUser.setLastLoginTime(currentDate); // 设置最后登陆时间
                                            currentUser.saveInBackground();
                                        }
                                    }

                                });
                        MLApplication.getInstance().setUserName(
                                UserService.getCurrentUserId());
                        MLApplication.getInstance().setPassword(
                                MD5.md5(UserService.getCurrentUserId()));

                        try {
                            // **
                            // 第一次登录或者之前logout后再登录，加载所有本地群和回话
                            // ** manually load all
                            // local groups
                            // and
                            // conversations in case we
                            // are auto
                            // login
                            EMChatManager.getInstance().loadAllConversations();
                            // 处理好友和群组
                            // processContacts();
                            mlCache = new MLCache(ctx);
                            mlCache.InitUser();
                            mlCache.getUserLike();
                            mlCache.getArticleLike();
                        } catch (Exception e) {
                            e.printStackTrace();
                            // 取好友或者群聊失败，不让进入主页面
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    if (mLoadingDialog.isShowing())
                                        mLoadingDialog.dismiss();
                                    MLApplication.getInstance().logout(null);
                                    ToolKits.toast(ctx,
                                            R.string.login_failure_failed);
                                    Intent infoInent = new Intent(ctx,
                                            TempMain.class);
                                    ctx.startActivity(infoInent);
                                    ((Activity) ctx).finish();

                                }
                            });
                            return;
                        }
                        // 更新当前用户的nickname
                        // 此方法的作用是在ios离线推送时能够显示用户nick
                        boolean updatenick = EMChatManager.getInstance()
                                .updateCurrentUserNick(
                                        MLApplication.currentUserNick.trim());
                        // if (!updatenick) {
                        // Log.e("LoginActivity",
                        // "update current user nick fail");
                        // }
                        if (!((Activity) ctx).isFinishing())
                            // 进入主页面
                            isLogin = true;
                        // Log.e("LoginActivity", "Login succeed");


                        MLApplication.getInstance().setIsLogin(true);
                        Intent intent = new Intent(ctx, Main.class);
                        ctx.startActivity(intent);
                        if (mLoadingDialog.isShowing())
                            mLoadingDialog.dismiss();
                        ((Activity) ctx).finish();

                    }

                    @Override
                    public void onProgress(int progress, String status) {
                        if (!mLoadingDialog.isShowing()) {
                            mLoadingDialog.show();
                        }
                    }

                    @Override
                    public void onError(final int code, final String message) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                isLogin = false;
                                logOut();
                                if (mLoadingDialog.isShowing())
                                    mLoadingDialog.dismiss();
                                ToolKits.toast(ctx,
                                        R.string.login_failure_failed);
                                Intent infoInent = new Intent(ctx,
                                        TempMain.class);
                                ctx.startActivity(infoInent);
                                ((Activity) ctx).finish();
                            }
                        });
                    }
                });
    }

    public void checkIsTimeOut() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat(
                "yyyy-MM-dd hh:mm:ss");
        String curDate = sDateFormat.format(new java.util.Date());
        String date = sDateFormat.format(UserService.getCurrentUser()
                .getLastLoginTime());
        try {
            Date d1 = sDateFormat.parse(curDate);
            Date d2 = sDateFormat.parse(date);
            long diff = (d1.getTime() - d2.getTime()) / 1000;// 这样得到秒级别
            // if (diff >= 60) {// 超过1分钟登陆
            if (diff >= 600000) {// 超过7天登陆
                if (mlCache != null) {
                    mlCache.clearCache();
                }
                MLCache.reloadContact(); // 重新refresh所有联系人
            }
        } catch (Exception e) {
        }
    }

    public void setLastLoginDate() {
        checkIsTimeOut();
        AVCloud.callFunctionInBackground("getNetTime", null,
                new FunctionCallback<Long>() {

                    @Override
                    public void done(Long time, AVException e) {
                        if (e == null) {
                            Date date = new Date(time);
                            MLUser currentUser = new MLUser();
                            currentUser.setObjectId(UserService.getCurrentUserId());
                            currentUser.setLastLoginTime(date); // 设置最后登陆时间
                            currentUser.saveInBackground();
                        }
                    }
                });
    }

    protected void runOnUiThread(Runnable runnable) {
        // TODO Auto-generated method stub

    }

    private void setUserHearder(String username, User user) {
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(HanziToPinyin.getInstance()
                    .get(headerName.substring(0, 1)).get(0).target.substring(0,
                            1).toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }

    }

    protected void logOut() {
        MLUser.logOut();
        MLApplication.getInstance().logout(null);
        if (UserService.getCurrentUser() != null) {
            cancleChannel();
        }
        // 退订之后需要重新保存 Installation
        AVInstallation.getCurrentInstallation().saveInBackground();
        MLApplication.getInstance().logout(new EMCallBack() {

            @Override
            public void onSuccess() {
                ((Activity) ctx).runOnUiThread(new Runnable() {
                    public void run() {
                        // 重新显示登陆页面
                        MLUser.logOut();
                        MLContext.deleteAll(); // 删除所有sharepreference
                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {

            }
        });
    }

    private void cancleChannel() {
        PushService.unsubscribe(ctx, UserService.getCurrentUserId());
        if (UserService.getCurrentUser().getType() == C.USER_TYPE_LOVER
                || UserService.getCurrentUser().getType() == C.USER_TYPE_RECOMMENDED) {
            if (UserService.getCurrentUser().getGender() == C.USER_GENDER_MALE) {
                PushService.unsubscribe(ctx, "SweetMale");
            } else if (UserService.getCurrentUser().getGender() == C.USER_GENDER_FEMALE) {
                PushService.unsubscribe(ctx, "SweetFemale");
            }
        }

    }

    public void setLoginListener(loginCompleteListener l) {
        if (null != l && mLoginCompleteListener != l) {
            mLoginCompleteListener = l;
        }
    }

    public interface loginCompleteListener {
        public void onComplate();
    }

}
